package com.mano.mall.web.shop.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.mano.commons.web.constants.WebConstants;
import com.mano.commons.web.utils.CookieUtils;
import com.mano.commons.web.utils.RandomValidateCodeUtil;
import com.mano.mall.api.dto.member.input.UserLoginInpDTO;
import com.mano.mall.api.dto.member.input.UserLogoutInputDTO;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.utils.MyBeanUtils;
import com.mano.commons.web.base.BaseWebController;
import com.mano.mall.web.shop.member.feign.MemberLoginServiceFeign;
import com.mano.mall.web.shop.member.req.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class LoginController extends BaseWebController {
	/**
	 * 跳转到登陆页面页面
	 */
	private static final String MB_LOGIN_FTL = "member/login";
	/**
	 * 重定向到首页
	 */
	private static final String REDIRECT_INDEX = "redirect:/";

	private static final String REDIRECT_LOGIN="redirect:/login";

	@Autowired
	private MemberLoginServiceFeign memberLoginServiceFeign;

	/**
	 * 跳转到登录页面
	 * 
	 * @return
	 */
	@GetMapping("/login")
	public String getLogin() {
		return MB_LOGIN_FTL;
	}

	/**
	 * 跳转到登录页面
	 * 
	 * @return
	 */
	@PostMapping("/login")
	public String postLogin(@ModelAttribute("loginVo") @Validated LoginVo loginVo, BindingResult bindingResult, Model model, HttpServletRequest request,
							HttpServletResponse response, HttpSession httpSession
	) {

		if(bindingResult.hasErrors()){
			// 获取第一个错误!
			String errorMsg = bindingResult.getFieldError().getDefaultMessage();
			setErrorMsg(model, errorMsg);
			return MB_LOGIN_FTL;
		}

		// 1.图形验证码判断
		String graphicCode = loginVo.getGraphicCode();
		if (!RandomValidateCodeUtil.checkVerify(graphicCode, httpSession)) {
			setErrorMsg(model, "图形验证码不正确!");
			return MB_LOGIN_FTL;
		}

		// 2.将vo转换为dto
		UserLoginInpDTO loginInpDTO = MyBeanUtils.doToDto(loginVo, UserLoginInpDTO.class);
		loginInpDTO.setLoginType(WebConstants.MEMBER_LOGIN_TYPE_PC);

		String info = webBrowserInfo(request);
		loginInpDTO.setDeviceInfor(info);

		BaseResponse<JSONObject> login = memberLoginServiceFeign.login(loginInpDTO);
		if(!isSuccess(login)){
			setErrorMsg(model, login.getMsg());
			return MB_LOGIN_FTL;

		}

		// 登录成功以后 要保存token回话信息到cookies  首页读取cookies 获取用户信息返回给页面
		// 2.将token存入到cookie中
		JSONObject data = login.getData();
		String token = data.getString("token");
		CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIES, token);
		// 登陆成功后，跳转到首页
		return REDIRECT_INDEX;
	}


    @GetMapping("/logout")
    public String postLogin(HttpServletRequest req,HttpServletResponse resp) {
		// 1. 根据session 获取 对应的token
		// 1.从cookie 中 获取 会员token
		String token = CookieUtils.getCookieValue(req, WebConstants.LOGIN_TOKEN_COOKIES);
		if(StringUtils.isBlank(token)){
			// 没有session 说明不在登录状态？
			log.info("没有token,检查是否已退出");
			return REDIRECT_LOGIN;
		}

//		String info = webBrowserInfo(req);
		UserLogoutInputDTO logoutInputDTO = new UserLogoutInputDTO();
		logoutInputDTO.setToken(token);
		memberLoginServiceFeign.logout(logoutInputDTO);

//		if(!isSuccess(response)){
//			setErrorMsg(model, login.getMsg());
//			return REDIRECT_LOGIN;
//		}


//		session.removeAttribute(WebConstants.LOGIN_TOKEN_COOKIES);
		// session 失效
//		session.invalidate();
		CookieUtils.deleteCookie(req,resp,WebConstants.LOGIN_TOKEN_COOKIES);

	    return REDIRECT_LOGIN;
    }
}
